<?php

/**
 *Form Controller
 *
 * @author Pavel Savchuk
 */
class Backend_FormController extends RCMS_Core_BaseController {

    public function init() {
        parent::init();
        $this->_checkLogin();
        $this->_model = new Backend_FormModel();
    }

    public function indexAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
    }


  /**
   * @method  adds new form
   * @return void
   */
    public function addformAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $form = new RCMS_Form_FormsForm();

        $form->setDecorators(array(
                array('ViewScript', array('viewScript' => 'forms/addform.phtml'))
            ));
        $name = $this->getRequest()->getParam('name');
        $pageId = $this->getRequest()->getParam('pageId');
        if(isset($pageId) && $pageId>0)
        {
            $pageObj = new RCMS_Object_Page_Page($pageId);
            $form->getElement('pageUrl')->setValue($pageObj->getUrl());
        }
        
        $model = new Backend_FormModel();
        
        $adminEmail = $this->_model->selectAdminEmail();
        $form->getElement('name')->setValue($name);
        $form->getElement('email')->setValue($adminEmail['admin_email']);
        $form->getElement('emailFrom')->setValue($adminEmail['admin_email']);
        $form->getElement('constantContactLogin')->setValue($model->selectConstantContactLogin());
        $form->getElement('constantContactPassword')->setValue($model->selectConstantContactPassword());
        $form->getElement('constantContactApikey')->setValue($model->selectConstantContactApikey());
        
        if(empty ($name))
        {
            throw new Exception('Form name is not set!');
        }
        
        $this->view->form = $form;
        $this->view->name = $name;

        if($this->getRequest()->isPost()) {
            if($this->view->form->isValid($this->getRequest()->getParams())) {
                $formObj = new RCMS_Object_Form_Form();

                $name           = htmlspecialchars($this->getRequest()->getParam('name'));
                $useSMTP        = $this->getRequest()->getParam('useSmtp');
                $code           = $this->getRequest()->getParam('code');
                $email          = htmlspecialchars($this->getRequest()->getParam('email'));
                $successMessage = $this->getRequest()->getParam('successMessage');
                $errorMessage   = htmlspecialchars($this->getRequest()->getParam('errorMessage'));
                $emailFrom      = htmlspecialchars($this->getRequest()->getParam('emailFrom'));
                $emailMessage   = htmlspecialchars($this->getRequest()->getParam('emailMessage'));
                $pageUrl        = $this->getRequest()->getParam('pageUrl');
				$autoReplySubj  = $this->getRequest()->getParam('autoReplySubj');
                $constantContact = $this->getRequest()->getParam('constantContact');
                $constantContactLogin = $this->getRequest()->getParam('constantContactLogin');
                $constantContactPassword = $this->getRequest()->getParam('constantContactPassword');
                $constantContactApikey = $this->getRequest()->getParam('constantContactApikey');
                $constantContactList = $this->getRequest()->getParam('ccListOfThemes');
				$trackFlag = intval($this->getRequest()->getParam('track'));
				if($trackFlag) {
					$formObj = $this->_applyTracking($formObj, $name);
				}
				$formObj->setTrack($trackFlag);
                $contactConstantRequest = array('constantContactLogin'=>$constantContactLogin, 'constantContactPassword'=>$constantContactPassword, 'constantContactApikey'=>$constantContactApikey);
                $selectConstantContactLogin = $model->selectConstantContactLogin();
                $selectConstantContactPassword = $model->selectConstantContactPassword();
                $selectConstantContactApikey = $model->selectConstantContactApikey();
                $model->deleteConstantContactLogin();
                $model->deleteConstantContactPassword();
                $model->deleteConstantContactApikey();
                foreach ($contactConstantRequest as $key=>$value){
                      $constantContactData = array('name'=> $key, 'value'=>$value);
                      $model->insertConstantContact($constantContactData);
                }
                
                $formObj->setName((isset($name))? $name : 'error');
                $formObj->setUseSMTP((isset($useSMTP))? $useSMTP :0);
                $formObj->setCode((isset($code))? $code : '');
                $formObj->setEmail((isset($email))? $email : '');
                $formObj->setSuccessMessage((isset($successMessage))? $successMessage : '');
                $formObj->setErrorMessage((isset($errorMessage))? $errorMessage : '');
                $formObj->setEmailFrom((isset($emailFrom))? $emailFrom : '');
                $formObj->setEmailMessage((isset($emailMessage))? $emailMessage : '');
				$formObj->setAutoReplySubj($autoReplySubj);
                $formObj->setConstantContact($constantContact);
                $formObj->setConstantContactList((isset($constantContactList))? serialize($constantContactList) : '');
                $flag = $formObj->save();               
                if($flag)
                {
                    $this->view->redirect = $this->getWebSiteUrl().$pageUrl.".html";
                }
            }else
            {
               $this->view->errorElements = $this->processErrors($this->view->form->getMessages());
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

  /**
   * @method  fiils form with existed data
   *@param <RCMS_Object_Form_Form> $formObj
   * @return void
   */
    public function fillForm(RCMS_Object_Form_Form $formObj)
    {
        $form = new RCMS_Form_FormsForm();
        $model = new Backend_FormModel();
        $constantContactList = unserialize($model->selectConstantContactList($formObj->getId()));
        $this->view->constantContactList = $constantContactList;
        $form->setDecorators(array(
                array('ViewScript', array('viewScript' => 'forms/editform.phtml'))
            ));
        $form->getElement('id')->setValue($formObj->getId());
        $form->getElement('name')->setValue($formObj->getName());
        $form->getElement('code')->setValue($formObj->getCode());
        $form->getElement('email')->setValue($formObj->getEmail());
        $form->getElement('emailFrom')->setValue($formObj->getEmailFrom());
        $form->getElement('useSmtp')->setValue($formObj->getUseSMTP());
        $form->getElement('emailMessage')->setValue($formObj->getEmailMessage());
        $form->getElement('successMessage')->setValue($formObj->getSuccessMessage());
        $form->getElement('errorMessage')->setValue($formObj->getErrorMessage());
        $form->getElement('constantContact')->setValue($model->selectConstantContactFlag($formObj->getId()));
        $form->getElement('constantContactLogin')->setValue($model->selectConstantContactLogin());
        $form->getElement('constantContactPassword')->setValue($model->selectConstantContactPassword());
        $form->getElement('constantContactApikey')->setValue($model->selectConstantContactApikey());
		$form->getElement('autoReplySubj')->setValue($formObj->getAutoReplySubj());
		$form->getElement('track')->setValue($formObj->getTrack());
		$trackingData = $formObj->getTrackingData();
		$form->getElement('trackCode')->setValue($trackingData['code']);
		$trackinPage = new RCMS_Object_Page_Page($trackingData['thxPageId']);
		$this->view->trackingPageUrl = $trackinPage->getUrl();
		unset($trackinPage);
        return $form;
    }

  /**
   * @method  edits form
   *
   * @return void
   */
    public function editformAction() {
        $this->_helper->getHelper('layout')->disableLayout();

        $formId = $this->getRequest()->getParam('formId');
        $pageId = $this->getRequest()->getParam('pageId');
        $this->view->pageId = $pageId;
        $this->view->formId = $formId;

        if($formId > 0 && $pageId > 0)
        {
            $formObj = new RCMS_Object_Form_Form($formId);
            $pageObj = new RCMS_Object_Page_Page($pageId);
            $form = $this->fillForm($formObj);
            $this->view->form = $form;
            $this->view->name= $formObj->getName();
            $model = new Backend_FormModel();
            $form->getElement('pageUrl')->setValue($pageObj->getUrl());
           
            if($this->getRequest()->isPost()) {
                if($this->view->form->isValid($this->getRequest()->getParams())) {
                    $name           = htmlspecialchars($this->getRequest()->getParam('name'));
                    $useSMTP        = $this->getRequest()->getParam('useSmtp');
                    $code           = $this->getRequest()->getParam('code');
                    $email          = htmlspecialchars($this->getRequest()->getParam('email'));
                    $successMessage = $this->getRequest()->getParam('successMessage');
                    $errorMessage   = htmlspecialchars($this->getRequest()->getParam('errorMessage'));
                    $emailFrom      = htmlspecialchars($this->getRequest()->getParam('emailFrom'));
                    $emailMessage   = $this->getRequest()->getParam('emailMessage');
                    $pageUrl        = $this->getRequest()->getParam('pageUrl');
					$autoReplySubj  = $this->getRequest()->getParam('autoReplySubj');
                    $constantContact = $this->getRequest()->getParam('constantContact');
                    $constantContactLogin = $this->getRequest()->getParam('constantContactLogin');
                    $constantContactPassword = $this->getRequest()->getParam('constantContactPassword');
                    $constantContactApikey = $this->getRequest()->getParam('constantContactApikey');
                    
                    $trackFlag    = intval($this->getRequest()->getParam('track'));
					if($trackFlag) {
						$formObj = $this->_applyTracking($formObj);
					}
					else {
						if($formObj->getTrack()) {
							$this->_removeTracking($formObj->getTrackingData());
							$formObj->setTrackingData('');
						}
					}
                    $contactConstantRequest = array('constantContactLogin'=>$constantContactLogin, 'constantContactPassword'=>$constantContactPassword, 'constantContactApikey'=>$constantContactApikey);
                    $selectConstantContactLogin = $model->selectConstantContactLogin();
                    $selectConstantContactPassword = $model->selectConstantContactPassword();
                    $selectConstantContactApikey = $model->selectConstantContactApikey();
                    $model->deleteConstantContactLogin();
                    $model->deleteConstantContactPassword();
                    $model->deleteConstantContactApikey();
                        foreach ($contactConstantRequest as $key=>$value){
                            $constantContactData = array('name'=> $key, 'value'=>$value);
                            $model->insertConstantContact($constantContactData);
                        }
                    $constantContactList = $this->getRequest()->getParam('ccListOfThemes');
                        if (count($constantContactList)!=0){
                            $constantContactList = serialize($constantContactList);
                            $model->updateConstantContactList($constantContactList, $formId);
                        }
                    $formObj->setTrack($trackFlag);
                    $formObj->setName((isset($name))? $name : 'error');
                    $formObj->setUseSMTP((isset($useSMTP))? $useSMTP :0);
                    $formObj->setCode((isset($code))? $code : '');
                    $formObj->setEmail((isset($email))? $email : '');
                    $formObj->setSuccessMessage((isset($successMessage))? $successMessage : '');
                    $formObj->setErrorMessage((isset($errorMessage))? $errorMessage : '');
                    $formObj->setEmailFrom((isset($emailFrom))? $emailFrom : '');
                    $formObj->setEmailMessage((isset($emailMessage))? $emailMessage : '');
                    $formObj->setAutoReplySubj($autoReplySubj);
                    $formObj->setConstantContact($constantContact);
                    
                    $flag = $formObj->save();
                    $this->view->redirect = $this->getWebSiteUrl() . $pageUrl . '.html';
                }
                else
                {
                     $this->view->errorElements = $this->processErrors($this->view->form->getMessages());
                }
            }

        }else
        {
            throw new Exception('Form Id or Page Id were not setted!');
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }


	private function _applyTracking(RCMS_Object_Form_Form $formObj, $formName = '') {
		$trackingCode = RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('trackCode'));
		$trackingData = $formObj->getTrackingData();
		if(!empty ($trackingData)) {
			if($trackingData['code'] != $trackingCode) {
				$trackingData['code'] = $trackingCode;
				$container = new RCMS_Object_Container_Container($trackingData['containerId']);
				$container->setContent($trackingData['code']);
				$container->save();
			}
		}
		else {
			$templateId = $this->_model->selectTemplateIdByName(RCMS_Object_Template_Template::TPL_DEFAULT);
			if($templateId) {
				$thxPageId = $this->_createThankYouTrackingPage($templateId, (!$formName) ? $formObj->getName() : $formName);
				if($thxPageId) {
					$containerId = $this->_createTrackingContainer($templateId, $thxPageId, $trackingCode);
					if($containerId) {
						$trackingData = array(
							'thxPageId'   => $thxPageId,
							'code'        => $trackingCode,
							'containerId' => $containerId
						);
					}
				}
			}
		}
		$this->_addSeoData($thxPageId, $trackingData['code']);
		$formObj->setTrackingData($trackingData);
		return $formObj;
	}

	private function _removeTracking($trackingData) {
		// removing thank you page
		$page = new RCMS_Object_Page_Page($trackingData['thxPageId']);
		$page->delete();

	}

	private function _createThankYouTrackingPage($templateId, $name) {
		$pageName     = str_replace('-', ' ', RCMS_Object_QuickConfig_QuickConfig::$thxPagesUrlPrefix) . ' ' . $name;
		$pageUrl      = 'frmtrack-' . str_replace(' ', '-', $pageName);
		$thxPageCatId = $this->_model->insertThxPageCategory('-1', $pageName);
		if($thxPageCatId) {
			$thankYouPage = new RCMS_Object_Page_Page();
			$thankYouPage->setCategoryId($thxPageCatId);
			$thankYouPage->setUrl($pageUrl);
			$thankYouPage->setTemplateId($templateId);
			$thankYouPage->setH1Tag($pageUrl);
			$thankYouPage->setTargetedKeyPhrase($pageUrl);
			$thankYouPage->setNavName($pageUrl);
			$thankYouPage->setHeaderTitle($pageUrl);
			$thankYouPage->setLastUpdate(date("Y-m-d H:i:s", time()));
			$thankYouPage->setShowInMenu(0);
			$thankYouPage->setIs404Page(0);
			$thankYouPage->setFeaturedId(0);
			return $thankYouPage->save();
		}
		return false;
	}

	private function _createTrackingContainer($templateId, $pageId, $code) {
		$template = new RCMS_Object_Template_Template($templateId);
		preg_match('/content:(.*)}/', $template->getContent(), $matches);
		if(isset($matches[1])) {
			$container = new RCMS_Object_Container_Container();
			$container->setType(RCMS_Object_Container_Container::C_TYPE_CONTENT);
			$container->setPageId($pageId);
			$container->setContent($code);
			$container->setUserId(unserialize($this->_session->currentUser)->getId());
			$container->setName($matches[1]);
			$container->setPublished(true);
			$container->setIsForSale(false);
			$container->setAllowComments(false);
			$container->setPublishingDate(date('Y-n-d G-i-s'));
			return $container->save();
		}
		return false;
	}


	private function _addSeoData($pageId, $seoData) {
		$updaterModel = new RCMS_Object_Updater_UpdaterModel();
		$result = $updaterModel->saveSeoData($seoData, null, $pageId);
	}

  /**
   * @method  deletes form
   *
   * @return void
   */
    public function deleteformAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $formId = $this->getRequest()->getParam('formId');
        $pageId = $this->getRequest()->getParam('pageId');



        if($formId>0 && $pageId>0)
        {
            $formObj = new RCMS_Object_Form_Form($formId);
            $pageObj = new RCMS_Object_Page_Page($pageId);
            if($formObj->delete())
            $this->_redirect($this->getWebSiteUrl()."".$pageObj->getUrl().".html");
        }else
        {
            throw new Exception(" Page Id or Form Id was not set!");
        }
    }

 public function processErrors($array)
    {
        $messages = array();
        $htmlUl = "";

        foreach ($array as $key => $value)
        {
            switch ($key)
            {
                case 'code':
                    if(isset($value['isEmpty']))
                    $messages[]="Content field can't be empty.";
                    if(isset($value['stringLengthTooShort']))
                    $messages[]="Content field can't less than 3 characters.";
                    break;

                case 'email':
                    if(isset($value['isEmpty']))
                    $messages[]="Mail To can't be empty.";
                    if(isset($value['regexNotMatch']))
                    $messages[]="Mail To is not valid.";
                    if(isset($value['stringLengthTooShort']))
                    $messages[]="Mail To field can't less than 3 characters.";
                     if(isset($value['stringLengthTooLong']))
                    $messages[]="Mail To field can't more than 255 characters.";
                    break;

                case 'emailFrom':
                    if(isset($value['isEmpty']))
                    $messages[]="Email From field can't be empty.";
                    if(isset($value['regexNotMatch']))
                   $messages[]="Email From is not valid.";
                    if(isset($value['stringLengthTooShort']))
                    $messages[]="Email From field can't less than 3 characters.";
                     if(isset($value['stringLengthTooLong']))
                    $messages[]="Email From field can't more than 255 characters.";
                    break;

                case 'successMessage':
                    if(isset($value['isEmpty']))
                    $messages[]="Success Message field can't be empty.";
                    if(isset($value['stringLengthTooShort']))
                    $messages[]="Success Message field can't be less than 3 characters.";
                    if(isset($value['stringLengthTooLong']))
                    $messages[]="Success Message field can't be more than 1800 characters.";
                    break;

                case 'errorMessage':
                    if(isset($value['isEmpty']))
                    $messages[]="Error Message field can't be empty.";
                    if(isset($value['stringLengthTooShort']))
                    $messages[]="Error Message field can't be less than 3 characters.";
                    if(isset($value['stringLengthTooLong']))
                    $messages[]="Error Message field can't be more than 1800 characters.";
                    break;

                case 'emailMessage':
                    if(isset($value['stringLengthTooShort']))
                    $messages[]="Email Message field can't be less than 3 characters.";
                    if(isset($value['stringLengthTooLong']))
                    $messages[]="Email Message field can't be more than 3800 characters.";
                    break;
            }
        }

        if(!empty($messages))
        {
            $htmlUl = "<ul>";
            foreach ($messages as $message)
            {
                $htmlUl .= "<li>".$message."</li>";
            }
            $htmlUl .= "<ul>";
            return $htmlUl;
        }
        return null;
    }


}
